package mbsl.ui.dialogs;

import static mbsl.util.SWTUtils.Direction.down;
import static mbsl.util.SWTUtils.Direction.left;
import static mbsl.util.SWTUtils.Direction.right;
import static mbsl.util.SWTUtils.Direction.up;
import mbsl.util.SWTUtils;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * A simple Input dialog.
 * <p>
 * The dialog is a {@link Dialog}, with a simple one-line text field the user can write in.
 */
public class Input extends Dialog<String> {
	public Input(Shell pParent, String pMessage, String pHeader) {
		super(pParent, pMessage, pHeader);
	}
	
	protected void addComponents(Shell pWindow, Label pLabel, final Button pConfirm) {
		pConfirm.setEnabled(false);
		
		// Text field
		final Text input = new Text(pWindow, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
		
		input.setLayoutData(SWTUtils.getFormData(200, SWT.DEFAULT,
				SWTUtils.getMeta(up, pLabel, 5),
				SWTUtils.getMeta(left, 0, 3),
				SWTUtils.getMeta(right, 100, -3),
				SWTUtils.getMeta(down, pConfirm, -5)
		));
		// OK button
		pConfirm.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent pE) {
				close(input.getText().trim());
			}
		});
		pConfirm.setEnabled(false);
		// A modify listener which activates the OK button if the field is non-empty
		input.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent pE) {
				pConfirm.setEnabled(!input.getText().trim().isEmpty());
			}
		});
		// Routes the event to the confirm button listener if enter is pressed
		input.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent pE) {
				if (pE.character == SWT.CR && pConfirm.isEnabled())
					pConfirm.notifyListeners(SWT.Selection, new Event());
			}
		});
		
		input.forceFocus();
	}
}
